package top.gelonggld.model;

import top.gelonggld.constants.PType;
import top.gelonggld.constants.Rex;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by gelon on 2017/5/27.
 */
public abstract class Paragraph extends BaseParagraph{

    public Annotation annotation;
    public List<Note> notes;
    public int bodyHead,bodyend;
    //注解之外的其他部分   用于代码分析
    public List<OutAnno> outAnnos;

    public Paragraph(int start, int end, String paragraphStr, int type) {
        super(start, end, paragraphStr, type);
    }


    public Annotation getAnnotation() {
        return annotation;
    }

    public List<Note> getNotes() {
        return notes;
    }

    public int getBodyHead() {
        return bodyHead;
    }

    public int getBodyend() {
        return bodyend;
    }

    public List<OutAnno> getOutAnnos() {
        return outAnnos;
    }

    public Annotation parseAnnotation() {
        int annoStart = paragraphStr.indexOf("/**");
        int annoEnd = paragraphStr.indexOf("*/")+ 2;
        if(annoStart == -1 || annoEnd == -1){
            return null ;
        }
        return new Annotation(start+annoStart,start+annoEnd,paragraphStr.substring(annoStart,annoEnd), PType.ANNOTATION);
    }

    @Override
    public void onPushDate(String paragraphStr) {
        annotation = parseAnnotation();
        if(annotation != null){
            parseOutAnno();
        }else{
            outAnnos.add(new OutAnno(start,end,paragraphStr,PType.OUT_ANNO));
        }
        notes = parseNotes();
    }

    @Override
    public void initDate() {
        outAnnos = new ArrayList<>();
        notes = new ArrayList<>();
    }


    public List<Note> parseNotes() {
        for (OutAnno oa : outAnnos){
            Pattern pattern = Pattern.compile(Rex.NOTE);
            Matcher matcher = pattern.matcher(oa.paragraphStr);
            while (matcher.find()){
                notes.add(new Note(matcher.start()+ start,matcher.end() + start,matcher.group(), PType.NOTE,matcher.group(1)));
            }
        }
        return notes;
    }


    public void parseOutAnno() {
        outAnnos.add(new OutAnno(start,start+ annotation.getStart(),paragraphStr.substring(0,annotation.getStart()-start),PType.OUT_ANNO));
        outAnnos.add(new OutAnno(annotation.getEnd(),end,paragraphStr.substring(annotation.getEnd()-start,end-start),PType.OUT_ANNO));
    }
}
